//
//  CatSettinVController.m
//  DoorBell
//
//  Created by Chun Hung Cheung on 2023/3/17.
//  Copyright © 2023 Chun Hung Cheung. All rights reserved.
//

#import "CatDetailSettingVController.h"
#import "CatSettingModel.h"
#import "CatSettingGroupModel.h"
#import "CatSettingCell.h"
#import "LPActionSheet.h"
//#import "SD78VoiceVController.h"
//#import "SD78Mp3Info.h"
//#import "YKSettingTableViewDetail.h"
//#import "YKSettingDetailModle.h"
//#import "DecoderG711.h"
//#import "VL0MonitorTimeSettingTableVController.h"

@interface CatDetailSettingVController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *settingTableview;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,assign)int version;
@property (nonatomic,strong)dispatch_source_t wake_up_timer;
@property(nonatomic, assign)BOOL cancelpost;
@property(nonatomic, assign)int upgrade_count;
@end

@implementation CatDetailSettingVController

- (void)viewDidLoad {
    [super viewDidLoad];
     self.view.backgroundColor = [HexChangeRGB colorWithHexString:@"#F5F5F5"];

    [self setup];
     self.settingTableview.backgroundColor = [HexChangeRGB colorWithHexString:@"#F5F5F5"];
    if (@available(iOS 11.0, *)) {
           self.settingTableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
           self.automaticallyAdjustsScrollViewInsets = NO;
    }
}


- (void)devstClick:(NSNotification*)notification
{
    /*
     {
         bid = 1fd834a600472ebe24cb01e03f9416d1;
         method = devst;
         name = "e0d31a150c6f-1fd834a6";
         remoteupg = 2;
         role = 27;
         status = 0;
         stat = 0;
         type = 27;
         uid = 1fd834a600472ebe24cb01e03f9416d1;
     }
    */
    
    NSDictionary *dict = (NSDictionary*)notification.object;
    NSString *bid = [dict objectForKey:@"bid"];
    if (![bid isEqualToString:self.bid]) {
         return;
    }

    if ([self.bid isEqualToString:bid] && [[dict objectForKey:@"stat"] intValue] == 1) {
        [SVProgressHUD dismiss];
         self.cancelpost = YES;
    }else{
         self.cancelpost = NO;
    }
    
    if (self.settingsType == 2) {
        
        [self reload_data];
    }
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"devst" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"devicesCheckUpdate" object:nil];//设备端升级返回结果
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"upgrade_mcu_res" object:nil];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(devstClick:) name:@"devst" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(devicesCheckUpdate:) name:@"devicesCheckUpdate" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(upgrade_mcu_update:) name:@"upgrade_mcu_res" object:nil];
    
  
    [self reload_data];
}

- (void)reload_data
{
    FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
    if(self.settingsType == 3){
       
    
       
       [self getdata:list.voice_status disturb_status:list.disturb_status];
   }else {
       
       
       [AFNHTTPSRequest httpsRequestWithUrl:[YKBusinessFramework check_cat_mcu_version:list.usb_vnum brand_id:list.brand_id] errorHint:^(id errorData) {
           NSLog(@"errorData---%@",errorData);
           
          [self getdata:NO disturb_status:NO];
           
       } result:^(id data) {
           NSLog(@"data---%@",data);
           
           /*
            {
                "code": 0,              // 只有0时表示有新版本
                "reason": "success",
                "data": {
                    "remoteupg": 1,    // 1-表示有新版本，0-没有新版本
                    "version": 10001   // 最新版本号
                }
            }
            
            */
            self.upgrade_count = 0;
            NSDictionary *dict =   [data objectForKey:@"data"];
            int remoteupg = [[dict objectForKey:@"remoteupg"] intValue];
         
            BOOL is_new = (remoteupg >=1 ) ? YES : NO;
           
            self.upgrade_count =  (remoteupg >=1 ) ? 1 : 0;
           
           [self getdata:is_new disturb_status:NO];
           
       }];
    
   }
   [self.settingTableview reloadData];
}

- (void)upgrade_mcu_update:(NSNotification*)notifacation
{
    /*
     {
         from = 5ddc97cd018ee7ba20d6128053cf6710;
         method = "upgrade_result";/ upgrade_third_result
         result = 0;
         to = 99c5e102026c8ddb4003112054ef007e;
     }
     */
    NSDictionary *recvMsg = [notifacation object];
    int result = [[recvMsg objectForKey:@"result"] intValue];
    if (result == 1)//设备端开始更新
    {
        if (![self.bid isEqualToString:[recvMsg objectForKey:@"from"]]) {
            return;
        }
          FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue([recvMsg objectForKey:@"from"])]] firstObject];
          list.mcu_upg_status = 50; // 显示升级标记
         if ([list bg_saveOrUpdate]) {
         }
        
        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Upgrading", nil)];
    
    }
    else if (result == 0)
    {
    
        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Upgrade failed", nil)];

    }
    else if (result == 3)
    {
       
        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Upgrade failed,battery level is low", nil)];
    }
    else if (result == 4)
    {
        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Upgrade failed,not enough memory storage in device", nil)];
     
    }
    else if (result == 2)
    {
        
        if (![self.bid isEqualToString:[recvMsg objectForKey:@"from"]]) {
            return;
        }
         FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue([recvMsg objectForKey:@"from"])]] firstObject];
         list.mcu_upg_status = 0; // 显示升级标记
        [list bg_saveOrUpdate];
        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"upgrade successful", nil)];
    }
    else if (result == 5)
    {
        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"No SD card, update failed", nil)];
    }else if (result == -1)
    {
        
        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Upgrade failed", nil)];
       
        FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue([recvMsg objectForKey:@"from"])]] firstObject];
        list.mcu_upg_status = 0; // 显示升级标记
       if ([list bg_saveOrUpdate]) {
       }
        
    }
}

- (void)devicesCheckUpdate:(NSNotification*)notifacation
{
    /*
     {
         from = 5ddc97cd018ee7ba20d6128053cf6710;
         method = "upgrade_result";/ upgrade_third_result
         result = 0;
         to = 99c5e102026c8ddb4003112054ef007e;
     }
     */
    NSDictionary *recvMsg = [notifacation object];
    int result = [[recvMsg objectForKey:@"result"] intValue];
    if (result == 1)//设备端开始更新
    {
        if (![self.bid isEqualToString:[recvMsg objectForKey:@"from"]]) {
            return;
        }
          FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue([recvMsg objectForKey:@"from"])]] firstObject];
          list.remoteupg = 50; // 显示升级标记
        if ([list bg_saveOrUpdate]) {
        }
        
        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Upgrading", nil)];
    
    }
    else if (result == 0)
    {
    
        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Upgrade failed", nil)];

    }
    else if (result == 3)
    {
       
        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Upgrade failed,battery level is low", nil)];
    }
    else if (result == 4)
    {
        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Upgrade failed,not enough memory storage in device", nil)];
     
    }
    else if (result == 2)
    {
        
        if (![self.bid isEqualToString:[recvMsg objectForKey:@"from"]]) {
            return;
        }
         FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue([recvMsg objectForKey:@"from"])]] firstObject];
         list.remoteupg = 50; // 显示升级标记
        [list bg_saveOrUpdate];

        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Upgrading", nil)];
    }
    else if (result == 5)
    {
        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"No SD card, update failed", nil)];
    }
}


- (void)setup
{
     UIButton *backbtn = [UIButton buttonWithType:UIButtonTypeCustom];
     backbtn.frame = CGRectMake(0,0,40,80);
     backbtn.contentHorizontalAlignment =  UIControlContentHorizontalAlignmentLeft;
    
    [backbtn setImage:[UIImage imageNamed:@"cat_alarm_back"] forState:UIControlStateNormal];
    [backbtn addTarget:self action:@selector(selectLeftActionClick) forControlEvents:UIControlEventTouchUpInside];
    [backbtn SG_imagePositionStyle:SGImagePositionStyleDefault spacing:5];
     self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backbtn];
 
    UILabel *titleLabel  = [[UILabel alloc]init];
    titleLabel.textColor = [HexChangeRGB colorWithHexString:@"#333333"];
    titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:20.0];
    switch (self.settingsType) {
        case 1:
        {
            titleLabel.text = @"基本功能设置";
        }
            break;
        case 2:
        case 4:
        {
            titleLabel.text = NSLocalizedString(@"设备信息",nil);
        }
            break;
        case 3:
        {
            titleLabel.text = NSLocalizedString(@"语音设置",nil);
        }
            break;
            
        default:
            break;
    }
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.frame = CGRectMake(0, 0, 80, 25);
     self.navigationItem.titleView = titleLabel;
}



- (void)selectLeftActionClick
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)getdata:(BOOL)ison disturb_status:(BOOL)disturb_status
{
    
    [self.dataArray removeAllObjects];
    
    FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
    
    switch (self.settingsType) {
    
        case 2:
        {
            FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
            CatSettingModel *model1 = [[CatSettingModel alloc]initWithTitle:NSLocalizedString(@"当前网络", nil) subTitle:list.wifi_rssi andType:5 status:NO];
            model1.wifi_name = list.wifi_ssid;
            model1.wifi_config = list.wifi_rssi;
            
            CatSettingModel *model2 = [[CatSettingModel alloc]initWithTitle:NSLocalizedString(@"序列号", nil)  subTitle:list.name andType:3 status:NO];
            
        
            NSString *title2;
            if (ison) {
                title2 =   NSLocalizedString(@"点击升级", nil);
            }else{
                if (list.mcu_upg_status == 50) {
                    title2 =  NSLocalizedString(@"升级中", nil);
                }else{
                    title2 =  NSLocalizedString(@"已是最新版本", nil);
                }
            }
            
            CatSettingModel *model4 = [[CatSettingModel alloc]initWithTitle:NSLocalizedString(@"设备版本",nil) subTitle:title2 andType:4 status:NO];
            CatSettingGroupModel *groupModel = [[CatSettingGroupModel alloc]init];
             groupModel.footerTitle = [NSString stringWithFormat:@"%@：%@",NSLocalizedString(@"设备当前版本", nil),list.usb_vnum];
             groupModel.dataArray = @[model1,model2,model4];
            [self.dataArray addObject:groupModel];
        
            
            NSString *title;
            if (list.remoteupg == 0) {
                title =  NSLocalizedString(@"已是最新版本", nil);;
            }else if (list.remoteupg == 50) {
                title =  NSLocalizedString(@"升级中", nil);;
            }else{
                title =   NSLocalizedString(@"点击升级", nil);
                self.upgrade_count += 1;
            }
            CatSettingModel *model3 = [[CatSettingModel alloc]initWithTitle:NSLocalizedString(@"可视对讲版本",nil) subTitle:title andType:4 status:NO];
        
            CatSettingGroupModel *groupModel2 = [[CatSettingGroupModel alloc]init];
             groupModel2.footerTitle = [NSString stringWithFormat:@"%@：%@",NSLocalizedString(@"设备当前版本", nil),list.vnum];
             groupModel2.dataArray = @[model3];
            [self.dataArray addObject:groupModel2];
            [self.settingTableview reloadData];
        }
            break;

        case 3:
        {
            YKIPinfo *info = [[YKIPinfo bg_find:@"YKIPinfo" where:nil] firstObject];
      

            [SVProgressHUD show];

            NSURL *url = [YKBusinessFramework get_g711a:_bid version:0];
            
            
            [AFNHTTPSRequest httpsRequestWithUrl:url errorHint:^(id errorData) {
                NSLog(@"data---%@",errorData);
                [SVProgressHUD dismiss];
                
            } result:^(id data) {
                NSLog(@"data---%@",data);
            
                 /*
                 {
                   "reason" : "success",
                   "data" : {
                     "version" : 7,
                     "fileId" : "AmYAAAABHABwdWJsaWMvcGV0L2s0bXpTOFhjeWVwVS5nNzExAAAAAAAC"
                   },
                   "code" : 0
                 }
                 */
                [SVProgressHUD dismiss];
                if ([[data objectForKey:@"code"] intValue] == 0) {
                    
                    NSDictionary *dict = [data objectForKey:@"data"];
                    NSFileManager  *fm  = [NSFileManager defaultManager];
                
                    int version = [[dict objectForKey:@"version"] intValue];
                    self.version = version;
                
                }
            }];
           
            
            [self.dataArray removeAllObjects];
             self.dataArray = nil;
            
          
            
            CatSettingModel *model1 = [[CatSettingModel alloc]initWithTitle:NSLocalizedString(@"出粮自动呼唤宠物",nil) subTitle:@"" andType:1 status:ison];
            CatSettingGroupModel *groupModel = [[CatSettingGroupModel alloc]init];
            groupModel.footerTitle = NSLocalizedString(@"每次出粮后自动播放语音呼唤宠物过来进食",nil);
            groupModel.dataArray = @[model1];
         
            NSString *str = [NSString stringWithFormat:@"%d %@",list.voice_count,NSLocalizedString(@"次",nil)];
            CatSettingModel *model2 = [[CatSettingModel alloc]initWithTitle:NSLocalizedString(@"循环播放次数",nil) subTitle:str andType:6 status:NO];
            CatSettingGroupModel *groupModel1 = [[CatSettingGroupModel alloc]init];
            groupModel1.footerTitle = NSLocalizedString(@"设置语音重复播放的次数，默认播放一次",nil);
            groupModel1.dataArray = @[model2];
            

            CatSettingModel *model4 = [[CatSettingModel alloc]initWithTitle:NSLocalizedString(@"夜间免打扰",nil) subTitle:@"" andType:1 status:disturb_status];
            model4.device_status = 1;
            CatSettingGroupModel *groupModel3 = [[CatSettingGroupModel alloc]init];
            groupModel3.footerTitle = NSLocalizedString(@"打开后可以关闭出粮语音播放",nil);
            groupModel3.groupTitle = NSLocalizedString(@"勿扰设置",nil);
            groupModel3.dataArray = @[model4];
            
            [self.dataArray addObject:groupModel];
            [self.dataArray addObject:groupModel1];
            [self.dataArray addObject:groupModel3];
            
            if (disturb_status) {
                 
                NSString *time = ( list.disturb_start_time.length > 0 &&  list.disturb_end_time.length > 0) ? [NSString stringWithFormat:@"%@-%@",list.disturb_start_time,list.disturb_end_time] : @"22:00-08:00";
                
                CatSettingModel *model5 = [[CatSettingModel alloc]initWithTitle:NSLocalizedString(@"勿扰时间段",nil) subTitle:time andType:6 status:NO];
                model5.device_status = 1;
                CatSettingGroupModel *groupModel4 = [[CatSettingGroupModel alloc]init];
                groupModel4.footerTitle = NSLocalizedString(@"在设置的时间段内喂食静音",nil);
                groupModel4.dataArray = @[model5];
                
                [self.dataArray addObject:groupModel4];
            }
            
            
        }
            break;
            
        default:
            break;
    }
 
    
}


- (UITableView*)settingTableview
{
     if(!_settingTableview){
         if(self.settingsType == 3){
             _settingTableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
         }else{
             _settingTableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
         }
         
         _settingTableview.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
         _settingTableview.dataSource = self;
         _settingTableview.delegate = self;
         
         UIView *view = [[UIView alloc] init];
         view.frame = CGRectMake(0, 0, 0 , 0.01);
      
         _settingTableview.tableHeaderView = view;
        [_settingTableview registerClass:[CatSettingCell class] forCellReuseIdentifier:@"CatSettingCell"];
         _settingTableview.rowHeight = 50;
        [self.view addSubview:_settingTableview];
        [_settingTableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
            make.top.equalTo(self.view.mas_top).offset([UIDevice dev_statusBarHeight] + 80);
            make.bottom.equalTo(self.view.mas_bottom);
        }];
    }
    return _settingTableview;
}


- (NSMutableArray*)dataArray
{
    if(!_dataArray){
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    CatSettingGroupModel *model = self.dataArray[section];
    return model.dataArray.count;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    CatSettingGroupModel *model = self.dataArray[indexPath.section];
    CatSettingModel  *datamodel = model.dataArray[indexPath.row];
    CatSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CatSettingCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = datamodel;
    cell.statusBlock = ^(BOOL isOn, CatSettingModel * _Nonnull model) {
        
        if ([model.title isEqualToString:NSLocalizedString(@"出粮自动呼唤宠物",nil)]) {
            
            [SVProgressHUD showWithDuration:10];
            FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
            
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
           [dict setValue:[NSString stringWithFormat:@"%d",isOn] forKey:@"voice_status"];
           [AFNHTTPSRequest httpsPostRequestWithUrl:[YKBusinessFramework update_shadow_settings:self.bid] errorHint:^(id errorData) {
               [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"Setting failed. Please try again later", nil)];
           }deleteDic:dict isFavorite:YES result:^(id data) {
                  NSLog(@"show_open_lock_button data-->%@",data);
                 [SVProgressHUD dismiss];
                 if ([[data objectForKey:@"code"] intValue] == 0)
                 {
                     if (list.status != 0) {
                         
                          NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[Tooles get_uid] ,self.bid];
                         [YKBusinessFramework equesSendData:Str];
                     }
                     [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"设置成功", nil) duration:1.5];
                     
                     FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
                     list.voice_status = isOn;
                    [list bg_saveOrUpdate];
                    [self getdata:isOn disturb_status:list.disturb_status];
                    [self.settingTableview reloadData];
                 }else{
                     
                    [self getdata:!isOn disturb_status:list.disturb_status];
                    [self.settingTableview reloadData];
                    [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"设置失败", nil)];
                     
                 }
           }];
            
            
        }else if ([model.title isEqualToString:NSLocalizedString(@"夜间免打扰",nil)]){
            
            [SVProgressHUD showWithDuration:10];
            FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
            
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
           [dict setValue:[NSString stringWithFormat:@"%d",isOn] forKey:@"disturb_status"];
           [AFNHTTPSRequest httpsPostRequestWithUrl:[YKBusinessFramework update_shadow_settings:self.bid] errorHint:^(id errorData) {
               [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"Setting failed. Please try again later", nil)];
           }deleteDic:dict isFavorite:YES result:^(id data) {
                  NSLog(@"disturb_status data-->%@",data);
                 [SVProgressHUD dismiss];
                 if ([[data objectForKey:@"code"] intValue] == 0)
                 {
                     [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"设置成功", nil) duration:1.5];
                     if (list.status != 0) {
                         
                          NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[Tooles get_uid] ,self.bid];
                         [YKBusinessFramework equesSendData:Str];
                         

                         // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
                         __block int timeout = 5; // 倒计时时间
                         dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                         dispatch_source_t new_time = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                         dispatch_source_set_timer(new_time,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
                         dispatch_source_set_event_handler(new_time, ^{
                             
                             {
                                 NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[Tooles get_uid] ,self.bid];
                                [YKBusinessFramework equesSendData:Str];
                                 
                                 timeout--;
                                 if (timeout <= 0) {
                                    dispatch_source_cancel(new_time);
                                 }
                             }
                             
                         });
                         dispatch_resume(new_time);
                     
                     }
                     
                     FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
                     list.disturb_status = isOn;
                    [list bg_saveOrUpdate];
                    [self getdata:list.voice_status disturb_status:isOn];
                    [self.settingTableview reloadData];
                 }else{
                     
                    [self getdata:list.voice_status disturb_status:!isOn];
                    [self.settingTableview reloadData];
                    [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"设置失败", nil)];
                     
                 }
           }];
            
        }
    };
    
    cell.updateBlock = ^(CatSettingModel * _Nonnull model) {
        

        if ([model.subTitle isEqualToString:NSLocalizedString(@"The Latest Version", nil)]) {
            
            [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"The Latest Version", nil)];
            
            return;
        }
        
         {
                
               __weak CatDetailSettingVController *weakSelf = self;
                if ([model.title isEqualToString:NSLocalizedString(@"可视对讲版本",nil)]) {
                    
                
                    FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
                    if (list.status == 2) {
                        [SVProgressHUD showWithDuration:15];
                        // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
                        __block int timeout = 30*200*5; // 倒计时时间
                        weakSelf.cancelpost = NO;
                        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                        weakSelf.wake_up_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                        dispatch_source_set_timer(weakSelf.wake_up_timer,dispatch_walltime(NULL, 0),200.0*NSEC_PER_MSEC, 0); //每秒执行
                        dispatch_source_set_event_handler(weakSelf.wake_up_timer, ^{
                            if(weakSelf.cancelpost){ // 倒计时结束，关闭
                                [YKBusinessFramework equesUpgradeDeviceWithUid:self.bid];
                                dispatch_source_cancel(weakSelf.wake_up_timer);
                                weakSelf.wake_up_timer = nil;
                            }else{
                                NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"],self.bid];
                                [YKBusinessFramework equesSendData:Str];
                                timeout-=200;
                                if (timeout <= 0) {
                                    dispatch_source_cancel(weakSelf.wake_up_timer);
                                    weakSelf.wake_up_timer = nil;
                                }
                            }
                        });
                        dispatch_resume(weakSelf.wake_up_timer);
                    }else if (list.status == 1){
                        [YKBusinessFramework equesUpgradeDeviceWithUid:self.bid];
                    }else{
                        [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"设备不在线", nil)];
                    }
                    
                } else{
                    
                    FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
                    
                    if (list.power_mode != 1) {
                        [SVProgressHUD showErrorWithStatus:@"为节省电池电量，电池供电下不建议升级！请切换适配器供电升级！" duration:5];
                        return;
                    }
                    
                    
                    if (self.upgrade_count >= 2) {
                        
                        [SVProgressHUD showErrorWithStatus:@"请先升级可视对讲版本,再升级设备版本"];
                        
                        return;
                    }
                    
                    
                    if (list.status == 2) {
                        [SVProgressHUD showWithDuration:15];
                        // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
                        __block int timeout = 30*200*5; // 倒计时时间
                        weakSelf.cancelpost = NO;
                        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                        weakSelf.wake_up_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                        dispatch_source_set_timer(weakSelf.wake_up_timer,dispatch_walltime(NULL, 0),200.0*NSEC_PER_MSEC, 0); //每秒执行
                        dispatch_source_set_event_handler(weakSelf.wake_up_timer, ^{
                            if(weakSelf.cancelpost){ // 倒计时结束，关闭
                                NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"upgrade_mcu\",\"from\":\"%@\",\"to\":\"%@\"}",[[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"],self.bid];
                               [YKBusinessFramework equesSendData:Str];
                                dispatch_source_cancel(weakSelf.wake_up_timer);
                                weakSelf.wake_up_timer = nil;
                            }else{
                                NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"],self.bid];
                                [YKBusinessFramework equesSendData:Str];
                                timeout-=200;
                                if (timeout <= 0) {
                                    dispatch_source_cancel(weakSelf.wake_up_timer);
                                    weakSelf.wake_up_timer = nil;
                                }
                            }
                        });
                        dispatch_resume(weakSelf.wake_up_timer);
                    }else if (list.status == 1){
                        
                         NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"upgrade_mcu\",\"from\":\"%@\",\"to\":\"%@\"}",[[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"],self.bid];
                        [YKBusinessFramework equesSendData:Str];
                        
                    }else{
                        [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"设备不在线", nil)];
                    }
                }
            }
    
    };
    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  
    CatSettingGroupModel *model = self.dataArray[indexPath.section];
    CatSettingModel  *datamodel = model.dataArray[indexPath.row];
    if([datamodel.title isEqualToString:NSLocalizedString(@"循环播放次数",nil)]){
        
        LPActionSheet *sheet = [[LPActionSheet alloc]initWithTitle:NSLocalizedString(@"循环播放次数",nil) cancelButtonTitle:@"取消" destructiveButtonTitle:@"" otherButtonTitles:@[NSLocalizedString(@"1次",nil),NSLocalizedString(@"2次",nil),NSLocalizedString(@"3次",nil),NSLocalizedString(@"4次",nil),NSLocalizedString(@"5次",nil)] handler:^(LPActionSheet *actionSheet, NSInteger index) {

            
            // -1 拍照 1 从相册选择
            NSLog(@"index == %ld",(long)index);
            
            if (index > 0) {
                
                [SVProgressHUD showWithDuration:10];
                FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
                
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
               [dict setValue:[NSString stringWithFormat:@"%ld",(long)index] forKey:@"voice_count"];
               [AFNHTTPSRequest httpsPostRequestWithUrl:[YKBusinessFramework update_shadow_settings:self.bid] errorHint:^(id errorData) {
                   [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"Setting failed. Please try again later", nil)];
               }deleteDic:dict isFavorite:YES result:^(id data) {
                      NSLog(@"disturb_status data-->%@",data);
                     [SVProgressHUD dismiss];
                     if ([[data objectForKey:@"code"] intValue] == 0)
                     {
                         [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"设置成功", nil) duration:1.5];
                         if (list.status != 0) {
                             
                              NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[Tooles get_uid] ,self.bid];
                             [YKBusinessFramework equesSendData:Str];
                             

                             // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
                             __block int timeout = 5; // 倒计时时间
                             dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                             dispatch_source_t new_time = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                             dispatch_source_set_timer(new_time,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
                             dispatch_source_set_event_handler(new_time, ^{
                                 
                                 {
                                     NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[Tooles get_uid] ,self.bid];
                                    [YKBusinessFramework equesSendData:Str];
                                     
                                     timeout--;
                                     if (timeout <= 0) {
                                        dispatch_source_cancel(new_time);
                                     }
                                 }
                             });
                             dispatch_resume(new_time);
                         }
                         
                         FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
                         list.voice_count = (int)index;
                        [list bg_saveOrUpdate];
                        [self getdata:list.voice_status disturb_status:list.disturb_status];
                        [self.settingTableview reloadData];
                     }else{
                         
                        [self getdata:list.voice_status disturb_status:list.disturb_status];
                        [self.settingTableview reloadData];
                        [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"设置失败", nil)];
                         
                     }
               }];
                
            }
        } andConfig:nil];
        [sheet show];
        

    }else if([datamodel.title isEqualToString:NSLocalizedString(@"勿扰时间段",nil)]){

//        "disturb_end_time" = "08:00";
//        "disturb_start_time" = "22:00";
        // 可以通过时间选择器 去定义时间 这个只是操作示范 时间间隔要大于1小时
        LPActionSheet *sheet = [[LPActionSheet alloc]initWithTitle:NSLocalizedString(@"勿扰时间段",nil) cancelButtonTitle:@"取消" destructiveButtonTitle:@"" otherButtonTitles:@[NSLocalizedString(@"22:00-08:00",nil),NSLocalizedString(@"23:00-09:00",nil),NSLocalizedString(@"24:00-10:00",nil),NSLocalizedString(@"可自定义",nil)] handler:^(LPActionSheet *actionSheet, NSInteger index) {
            
            
            if (index > 0) {
                
                [SVProgressHUD showWithDuration:10];
                FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
                
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                [dict setValue:@"23:00" forKey:@"disturb_start_time"];
                [dict setValue:@"09:00" forKey:@"disturb_end_time"];
               [AFNHTTPSRequest httpsPostRequestWithUrl:[YKBusinessFramework update_shadow_settings:self.bid] errorHint:^(id errorData) {
                   [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"Setting failed. Please try again later", nil)];
               }deleteDic:dict isFavorite:YES result:^(id data) {
                      NSLog(@"disturb_status data-->%@",data);
                     [SVProgressHUD dismiss];
                     if ([[data objectForKey:@"code"] intValue] == 0)
                     {
                         [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"设置成功", nil) duration:1.5];
                         if (list.status != 0) {
                             
                              NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[Tooles get_uid] ,self.bid];
                             [YKBusinessFramework equesSendData:Str];
                             

                             // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
                             __block int timeout = 5; // 倒计时时间
                             dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                             dispatch_source_t new_time = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                             dispatch_source_set_timer(new_time,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
                             dispatch_source_set_event_handler(new_time, ^{
                                 
                                 {
                                     NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[Tooles get_uid] ,self.bid];
                                    [YKBusinessFramework equesSendData:Str];
                                     
                                     timeout--;
                                     if (timeout <= 0) {
                                        dispatch_source_cancel(new_time);
                                     }
                                 }
                             });
                             dispatch_resume(new_time);
                         }
                         
                         FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
                         list.disturb_start_time = @"23:00";
                         list.disturb_end_time = @"08:00";
                        [list bg_saveOrUpdate];
                        [self getdata:list.voice_status disturb_status:list.disturb_status];
                        [self.settingTableview reloadData];
                     }else{
                         
                        [self getdata:list.voice_status disturb_status:list.disturb_status];
                        [self.settingTableview reloadData];
                        [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"设置失败", nil)];
                         
                     }
               }];
                
            }
            
            
        } andConfig:nil];
        [sheet show];
        
    }
        
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    CatSettingGroupModel *model = self.dataArray[section];
    if(model.groupTitle.length > 0){
        return 20;
    }else{
        return 0.1;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    CatSettingGroupModel *model = self.dataArray[section];
    if(model.footerTitle.length > 0){
        return 20;
    }else{
        return 0.1;
    }
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
     UIView *view = [[UIView alloc]init];
     view.backgroundColor = [UIColor clearColor];
    CatSettingGroupModel *model = self.dataArray[section];
    if(model.groupTitle.length > 0){
        UILabel *_subTitleLabel = [[UILabel alloc]init];
        [view addSubview:_subTitleLabel];
        _subTitleLabel.textColor = [HexChangeRGB colorWithHexString:@"#778CA2"];
        _subTitleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:13.0];
        _subTitleLabel.numberOfLines = 0;
        _subTitleLabel.textAlignment = NSTextAlignmentLeft;
       [_subTitleLabel sizeToFit];
       [_subTitleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
          make.left.equalTo(view.mas_left).offset(14);
          make.right.equalTo(view.mas_right).offset(-14);
          make.bottom.equalTo(view.mas_bottom);
       }];
        _subTitleLabel.text = model.groupTitle;
    }
     return view;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
     UIView *view = [[UIView alloc]init];
     view.backgroundColor = [UIColor clearColor];
     CatSettingGroupModel *model = self.dataArray[section];
     if(model.footerTitle.length > 0){
        UILabel *_subTitleLabel = [[UILabel alloc]init];
        [view addSubview:_subTitleLabel];
         if (self.settingsType == 3) {
             _subTitleLabel.textColor = [HexChangeRGB colorWithHexString:@"#808080"];
         }else{
             _subTitleLabel.textColor = [HexChangeRGB colorWithHexString:@"#778CA2"];
         }
        _subTitleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:13.0];
        _subTitleLabel.numberOfLines = 0;
        _subTitleLabel.textAlignment = NSTextAlignmentLeft;
       [_subTitleLabel sizeToFit];
       [_subTitleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
          make.left.equalTo(view.mas_left).offset(14);
          make.right.equalTo(view.mas_right).offset(-14);
          make.top.equalTo(view.mas_top).offset(5);
       }];
        _subTitleLabel.text = model.footerTitle;
    }

    return view;
}




@end
